package models

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"token-for-token/global"
)

type ChainToChain struct {
	Id             primitive.ObjectID   `bson:"_id ,omitempty"`
	ChainConfigId0 string               `bson:"chainConfigId0"`
	Token0         string               `bson:"token0"`
	ChainConfigId1 string               `bson:"chainConfigId1"`
	Token1         string               `bson:"token1"`
	UserId         string               `bson:"userId"`
	Rate           primitive.Decimal128 `bson:"rate"`
	MaxNumber      int64                `bson:"maxNumber"`
}

func (c *ChainToChain) GetChainToChainInfoForId(id string) error {
	user := global.DBEngine.Database(global.DbConfig.DbName).Collection("chain_to_chain")
	// 将字符串ID转换为ObjectID
	objID, err := primitive.ObjectIDFromHex(id)
	if err != nil {
		return err
	}
	filter := bson.M{"_id": objID}
	err = user.FindOne(context.Background(), filter).Decode(&c)
	return err
}

func (c *ChainToChain) GetInfoByParams() error {
	user := global.DBEngine.Database(global.DbConfig.DbName).Collection("chain_to_chain")
	filter := bson.M{}
	if c.ChainConfigId0 != "" {
		filter["chainConfigId0"] = c.ChainConfigId0
	}
	if c.ChainConfigId1 != "" {
		filter["chainConfigId1"] = c.ChainConfigId1
	}
	if c.UserId != "" {
		filter["userId"] = c.UserId
	}
	if c.Token0 != "" {
		filter["token0"] = c.Token0
	}
	if c.Token1 != "" {
		filter["token1"] = c.Token1
	}
	err := user.FindOne(context.Background(), filter).Decode(&c)
	return err
}
